/**
 * @created by zhangpeng18 on 2019-8-5 10:40:22
 * @updated by
 * @description Java类驱动管理
 */
define([
  './themes/lang/' + window.YUFP_SYS_CONFIG.language + '/pages/content/systemManager/passwordManager/passwordManager.js',
  './libs/jsencrypt/jsencrypt.min.js'
],function (require, exports) {
	/**
	 * 页面加载完成时触发
	 * @param hashCode 路由ID
	 * @param data 传递数据对象
	 * @param cite 页面站点信息
	 */
	exports.ready = function (hashCode, data, cite) {
		yufp.custom.vue({
			el: cite.el,
			data: function () {

				var _this = this;
				/**
				 * 校验自定义参数代码字段，必须以 $ 开头
				 */
				var paramCodeValidate = function (rule, value, callback) {
					var reg = /^\$/;
					if (value && reg.test(value)) {
						callback();
					} else if (value && !reg.test(value)) {
						callback(new Error('自定义参数代码字段，请以 $ 开头'));
					} else if (value === '') {
						callback(new Error('自定义参数代码字段，请以 $ 开头'));
					} else {
						callback();
					}
				};
				/*定义校验规则，只能填字母数字 下划线*/
				var valiCodes = function (rule, value, callback) {
					var reg = /^[0-9a-zA-Z_]{1,}$/;
					if (value && value.trim() && reg.test(value)) {
						if (value.length > 64) {
							callback(new Error('长度不能大于64位'));
						} else {
							callback();
						}
					} else if (value && value.trim() && !reg.test(value)) {
						callback(new Error('能填字母、数字和下划线'));
					} else {
						callback();
					}
				};
				return {
					testloading:false,
					tbHeight:'100%',
					searchFormdata: {},
					appNameDisabled: false,
					addFnButton: !yufp.session.checkCtrl('addFn'),
					updateFnButton: !yufp.session.checkCtrl('updateFn'),
					deleteFnButton: !yufp.session.checkCtrl('deleteFn'),
					treeDataUrl: "api/use/plats/apps/getTreeWftList",
					dataUrl: 'api/use/plats/rdbcfg/queryList',
					saveBtnShow: true,
					cancelBtnShow: true,
					addBtnShow: false,
					oldPWD:"",
					formdata: {},
					async: false,
					param: { UNITID: '0000', LEVELUNIT: '1' },
					rule: [
						{ validator: paramCodeValidate, trigger: 'blur' }
					],
					height: yufp.frame.size().height - 38,
					dialogVisible: false,
					formDisabled: false,
					classCodeDisabled: false,
					viewTitleArrry: ['数据库连接添加', '数据库连接修改', '数据库连接查看'],
					viewTitle: '',
					propTabaleData: [],
					saveDisabled: false,
					appCodeShow: true,
					appShowName: "aaa",
					nodeData: '', // 在新增表格数据时需要先获取当前树节点，再把一条新的记录加到这个节点下的表格里,
					nodeLeaf: false,
					isDisabledAppName: false,
					isReadOnly: false,
					queryName: "",
					databaseServerAllField: [{
						columnCount: 2,
						fields: [
							{
								field: 'classCode',
								label: '连接代码:',
								disabled: false,
								rules: [
									{ validator: valiCodes, trigger: 'blur' },
									{ required: true, trigger: 'blur', message: '不能为空' }
								]
							},
							{
								field: 'className',
								label: '连接名称:',
								rules: [
									{ required: true, max: 120, message: '长度小于120字节', trigger: 'blur' }]
							},
							{
								field: 'dataType',
								label: '数据库类型:',
								type: "select",
								dataCode: "RDB_TYPE",

								rules: [
									{ required: true, message: '必填项', trigger: 'blur' }]
							},
							{
								field: 'configMethod',
								label: '配置方式:',
								type: "select",
								dataCode: "CONFIG_METHOD",
								value: "1",
								change: function (val) {
									_this.changeConfigMethod(val);
								},
								rules: [
									{ required: true, message: '必填项', trigger: 'blur' }]

							},
							{
								field: 'username',
								label: '用户名:',
								rules: [
									{ required: true, message: '必填项', trigger: 'blur' },
									{ max: 64, message: '输入值过长', trigger: 'blur' }]
							},
							{
								field: 'password',
								label: '密码:',
								type: 'password',
								rules: [
									{ required: true, message: '必填项', trigger: 'blur' },
									{ max: 64, message: '输入值过长', trigger: 'blur' }]
							},
							{
								field: 'ipAddr',
								label: '服务器地址:',
								rules: [
									{ required: true, message: '必填项', trigger: 'blur' },
									{ max: 32, message: '输入值过长', trigger: 'blur' }]
							},
							{
								field: 'dbPort',
								label: '端口:',
								rules: [
									{ required: true, message: '必填项', trigger: 'blur' },
									{ max: 64, message: '输入值过长', trigger: 'blur' },
									{ message: '请输入数字', validator: yufp.validator.number }]
							},
							{
								field: 'dbName',
								label: '实例名:',
								rules: [
									{ required: true, message: '必填项', trigger: 'blur' },
									{ max: 64, message: '输入值过长', trigger: 'blur' }]
							}
						]
					}, {
						columnCount: 1,
						fields: [
							{
								label: "连接位置",
								field: "location",
								rows: 2,
								type: "textarea",
								rules: [
									{ required: true, message: '必填项', trigger: 'blur' }]
							}
							, {
								label: "备注",
								field: "remark",
								rows: 3,
								type: "textarea"
							}]

					}
					],

					saveButtons: [

						{
							label: '测试连接', type: 'primary', hidden: false, op: 'submit', click: function (model, valid) {
								_this.testConnect();

							}
						},
						{
							label: '取消', hidden: false, click: function (model) {
								_this.cancelFn();
							}
						},

						{
							label: '保存', type: 'primary', hidden: false, op: 'submit', disabled: this.saveDisabled, click: function (model, valid) {
								_this.saveFn();
							}
						},

					],

					//isReadOnly: false,
					agentIds: [
					],
					nodeTemp: {},
				};
			},
			mounted() {
				var _this = this;
				_this.$nextTick(function(){
						var tableBox = _this.$refs.tableBox;
						let a = tableBox.getBoundingClientRect().top + 28;
						var theight = `calc(100vh - ${a}px - 8px)`;
						_this.tbHeight = theight;		
				});
			},
			methods: {

				reloadData: function () {
					var _this = this;

					_this.searchFormdata.appCode = _this.nodeTemp.appCode;
					//var paramObj = _this.searchFormdata;
					_this.$refs.refTable.remoteData(_this.searchFormdata);
				},

				/**
				 * 取消
				 */
				cancelFn: function () {
					var _this = this;
					_this.dialogVisible = false;
				},
				/**
				 * 保存
				 */
				saveFn: function () {

					var _this = this;
					var validate = false;
					_this.$refs.refForm.validate(function (valid) {
						validate = valid;
					});
					if (!validate) {
						return;
					}

					//_this.checkClassCode(validate);

					if (!validate) {
						return;
					}

					var paramObj = _this.$refs.refForm.formModel;


					let urlparam = "";
					if (_this.addFlag) {
						paramObj.appCode = _this.nodeTemp.appCode;
						urlparam = 'api/use/plats/rdbcfg/saveUseRdbCfgPo';
					} else {
						urlparam = 'api/use/plats/rdbcfg/updateUseRdbCfgPo';
					}
					
					var objTO={};
					for(i in paramObj){
						objTO[i]=paramObj[i];
					}
					if(_this.oldPWD!=paramObj.password){
						var encrypt = new JSEncrypt();
						encrypt.setPublicKey(yufp.util.getRSAPublicKey());
						var encryptPwd = encrypt.encrypt(paramObj.password);
						objTO.password=encryptPwd;
						objTO.enType="RSA";
					}else{
						objTO.enType="DES";
					}
					

					yufp.service.request({
						method: 'POST',
						url: urlparam,
						data: objTO,
						callback: function (code, message, response) {

							if (response.code == 0) {
								_this.reloadData();
								_this.$message('操作成功');
								_this.dialogVisible = false;
							} else {
								_this.$message({ message: response.message, type: "warning" });
							}
						}
					});

				},
				/**
				 * 控制保存按钮、xdialog、表单的状态
				 * @param viewType 表单类型
				 * @param editable 可编辑,默认false
				 */
				switchStatus: function (viewType, editable) {
					var _this = this;
					_this.viewType = viewType;
					_this.dialogVisible = true;
					_this.formDisabled = !editable;
					_this.saveBtnShow = editable;
					_this.cancelBtnShow = editable;
				},


				changeConfigMethod: function (val) {
					const _this = this;
					_this.$set(_this.databaseServerAllField[0].fields[6], 'hidden', val === '0');
					_this.$set(_this.databaseServerAllField[0].fields[7], 'hidden', val === '0');
					_this.$set(_this.databaseServerAllField[0].fields[8], 'hidden', val === '0');
					_this.$set(_this.databaseServerAllField[1].fields[0], 'hidden', val === '1');

					_this.$set(_this.databaseServerAllField[0].fields[6].rules[0], 'required', val === '1');
					_this.$set(_this.databaseServerAllField[0].fields[7].rules[0], 'required', val === '1');
					_this.$set(_this.databaseServerAllField[0].fields[8].rules[0], 'required', val === '1');
					_this.$set(_this.databaseServerAllField[1].fields[0].rules[0], 'required', val === '0');
				},

				/**
				 * 点击树的结点，加载对应的数据
				 */
				nodeClickFn: function (nodeData, node, self) {
					var _this = this;
					var nodeApp = "";
					var appName = "";
					if (nodeData.appCode != '0000') {
						_this.nodeLeaf = true;
						_this.appShowName = nodeData.appName;
						_this.appNameDisabled = true;
						nodeApp = nodeData.appCode;
						appName = nodeData.appName;
						this.searchFormdata.appName = appName;
					} else {
						_this.nodeLeaf = false;
						_this.appNameDisabled = false;
						_this.searchFormdata.appName = "";
						_this.searchFormdata.appCode = "";
					}

					_this.appCodeShow = !_this.nodeLeaf;
					_this.nodeTemp.appCode = nodeApp;
					_this.isDisabledAppName = _this.nodeLeaf;
					_this.reloadData();

					//_this.$refs.refTable.remoteData({ appCode: nodeApp });

				},
				testConnect: function () {
					var _this = this;

					var validate = false;
					_this.$refs.refForm.validate(function (valid) {
						validate = valid;
					});
					if (!validate) {
						return;
					}
					_this.testloading = true;
					var objTMP=_this.$refs.refForm.formModel;
					var objTO={};
					for(i in objTMP){
						objTO[i]=objTMP[i];
					}
					if(objTMP.password!=_this.oldPWD){
						var encrypt = new JSEncrypt();
						encrypt.setPublicKey(yufp.util.getRSAPublicKey());
						var encryptPwd = encrypt.encrypt(objTMP.password);
						objTO.password=encryptPwd;
						objTO.enType="RSA";
					}else{
						objTO.enType="DES";
					}
					yufp.service.request({
						method: 'POST',
						url: "api/use/plats/rdbcfg/getConnTest",
						data: objTO,
						callback: function (code, message, response) {
							_this.testloading = false;
							if (response.code != 0) {
								_this.$message("连接失败，请检查参数");
							} else {
								if (response.data == true) {
									_this.$message('连接成功');
								} else {
									_this.$message("连接失败，请检查参数");
								}
							}
						}
					});
				},
				/**
				 * 新增
				 */
				addFn: function () {
					var _this = this;
					_this.oldPWD="";
					_this.saveDisabled = false;
					_this.isReadOnly = false;
					_this.dialogVisible = true;
					_this.viewTitle = _this.viewTitleArrry[0];
					_this.addFlag = true;
					// _this.databaseServerAllField[0].fields[0].disabled = false;
					//_this.$set(_this.databaseServerAllField[0].fields[0], 'readonly',  _this.isReadOnly );
					//_this.$set(_this.databaseServerAllField[0].fields[0], 'disabled',  _this.isReadOnly );
					_this.$set(_this.saveButtons[2], 'disabled', _this.saveDisabled);
					_this.$set(_this.saveButtons[2], 'type', "primary");

					_this.$nextTick(function () {
						_this.$refs.refForm.switch(_this.databaseServerAllField[0].fields[0].field, 'disabled', false);
						_this.$refs.refForm.resetFields();
						document.querySelector("input[type='password']").autocomplete="new-password";
					});


				},
				/**
				 * 修改
				 */
				modifyFn: function () {
					var _this = this;
					_this.saveDisabled = false;
					if (_this.$refs.refTable.selections.length != 1) {
						_this.$message({ message: '请先选择一条记录', type: 'warning', duration: 6000 });
						return;
					}
					_this.isReadOnly = true;
					_this.viewTitle = _this.viewTitleArrry[1];
					_this.dialogVisible = true;
					_this.addFlag = false;
					_this.refTemp = _this.$refs.refTable.selections[0];
					//_this.$set(_this.databaseServerAllField[0].fields[0], 'readonly',  _this.isReadOnly );
					//_this.$set(_this.databaseServerAllField[0].fields[0], 'disabled',  _this.isReadOnly );
					// _this.databaseServerAllField[0].fields[0].disabled = true;
					_this.oldPWD=_this.refTemp.password;
					_this.$set(_this.saveButtons[2], 'disabled', _this.saveDisabled);
					_this.$set(_this.saveButtons[2], 'type', "primary");
					_this.$nextTick(function () {
						_this.$refs.refForm.switch(_this.databaseServerAllField[0].fields[0].field, 'disabled', true);
						_this.$refs.refForm.resetFields();
						document.querySelector("input[type='password']").autocomplete="new-password";
						_this.refTemp.configMethod = "1";
						_this.$refs.refForm.formModel = yufp.clone(_this.refTemp, {});
						//yufp.clone(_this.refTemp, _this.formdata);

					});


				},


				viewFn: function (obj) {
					var _this = this;
					_this.saveDisabled = true;
					_this.isReadOnly = true;
					_this.viewTitle = _this.viewTitleArrry[2];
					_this.dialogVisible = true;
					_this.addFlag = false;
					_this.refTemp = obj;
					_this.oldPWD=_this.refTemp.password;
					// _this.$set(_this.databaseServerAllField[0].fields[0], 'readonly',  _this.isReadOnly );
					_this.$set(_this.saveButtons[2], 'disabled', _this.saveDisabled);
					_this.$set(_this.saveButtons[2], 'type', "info");
					_this.$nextTick(function () {
						_this.$refs.refForm.switch(_this.databaseServerAllField[0].fields[0].field, 'disabled', true);
						_this.$refs.refForm.resetFields();
						_this.refTemp.configMethod = "1";
						document.querySelector("input[type='password']").autocomplete="new-password";
						_this.$refs.refForm.formModel = yufp.clone(_this.refTemp, {});
						//yufp.clone(_this.refTemp, _this.formdata);

					});

				},

				/**
				 * 删除
				 */
				deleteFn: function () {
					var _this = this;
					var selections = _this.$refs.refTable.selections;
					if (selections.length < 1) {
						_this.$message({ message: '请先至少选择一条记录', type: 'warning',duration: 6000 });
						return;
					}
					var len = selections.length, arr = [];
					for (var i = 0; i < len; i++) {
						arr.push(selections[i].id);
					}
					_this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
						center: true,
						callback: function (action) {
							if (action === 'confirm') {
								yufp.service.request({
									method: 'DELETE',
									url: "api/use/plats/rdbcfg/deleteUseRdbCfgPo",
									data: selections[0],
									callback: function (code, message, response) {
										if (response.code != 0) {
											isOk = false;
											_this.$message(response.message);
										} else {
											_this.$message('操作成功');
											_this.reloadData();

										}

									}
								});
							}
						}
					});
				},
				checkClassCode: function (isOk) {

					var _this = this;
					var paramObj = _this.formdata;
					paramObj.useParamValues = [];
					if (!_this.addFlag) {
						return;
					}

					yufp.service.request({
						method: 'GET',
						url: "api/use/plats/dscfg/checkClassCode",
						data: paramObj,
						async: false,
						callback: function (code, message, response) {
							if (response.code != 0) {
								isOk = false;
								_this.$message(response.message);
							} else {
								if (!response.data) {
									isOk = false;
									_this.$message('该驱动缩写在系统中已经存在');
								}
							}

						}
					});
				},
			},

		});
	};
	exports.destroy = function () {
		console.log('页面下载器', arguments);
	}
});